
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes/index');
var http = require('http');;
var path = require('path');
var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(express);
var setting = require('./setting');
var fs = require("fs");
var accessLogfile = fs.createWriteStream('access.log', {flags:'a'});
var errorLogfile = fs.createWriteStream('error.log', {flags:'a'})

var app = express();

// all environments
app.configure(function(){
	app.use(express.logger({stream:accessLogfile}));

	app.set('port', process.env.PORT || 3000);
	app.set('views', path.join(__dirname, 'views'));
	app.set('view engine', 'ejs');
	app.use(flash());
	app.use(express.bodyParser());
	app.use(express.cookieParser());
	app.use(express.session({
		secret:setting.cookieSecret,
		store:new MongoStore({
			db:setting.db
		})
	}));
	app.use(express.favicon());
	app.use(express.logger('dev'));
	app.use(express.json());
	app.use(express.urlencoded());
	app.use(express.methodOverride());
	app.use(express.static(path.join(__dirname, 'public')));

	//将flash中的数据发送到前端
	app.use(function(req, res, next){
		res.locals.user = req.session.user;
		var success = req.flash('success');
		res.locals.success = success.length ? success : null;
		// var error = req.flash('error');

		res.locals.error = req.flash('error').length ? req.flash('error') : null;
		console.log('--->error:' + res.locals.error + "<---");
		next();

	});

	app.use(app.router);
	routes(app);
});

app.configure('production', function(){
	app.error(function(err, req, res, next){
		var meta = '[' + new Date() + ']' + req.url + '\n';
		errorLogfile.write(meta + err.stack + '\n');
		next();
	});
});

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler({dumpException:true, showStack:true}));
}

if(!module.parent){
	app.listen(3000);
	console.log('Express server listening on port %d in %s mode', app.address().port, app.settings.env);
}
/*http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
*/